import { onBeforeUnmount, ref } from 'vue'
import dayjs from 'dayjs'

export const useTime = () => {
    const weekList = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    const timeInfo = ref({})

    const initTime = () => {
        const now = dayjs()
        const noon = now.hour(12).minute(0).second(0).millisecond(0)
        let timeRange
        if (now.isBefore(noon)) {
            timeRange = '上午'
        } else {
            timeRange = '下午'
        }
        const time = now.format('hh:mm:ss')
        const date = now.format('YYYY[年]MM[月]DD[日]')
        const week = weekList[now.day()]
        Object.assign(timeInfo.value, { now, date, timeRange, time, week })
    }

    initTime()

    const timer = setInterval(() => {
        initTime()
    }, 1000)

    onBeforeUnmount(() => {
        clearInterval(timer)
    })

    return {
        timeInfo
    }
}